<template>
  <!-- destroy-on-close: 关闭之后销毁组件 -->
  <FormDrawer
    ref="formDrawerRef"
    title="设置商品详情"
    @submit="submit"
    @cancel="handleCancel"
    :destroy-on-close="true"
  >
    <el-form :model="form" ref="formRef">
      <el-form-item>
        <Editor v-model="form.content" />
      </el-form-item>
    </el-form>
  </FormDrawer>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { readGoodsApi, updateGoodsApi } from '@/api/goods'
  import FormDrawer from '@/components/FormDrawer.vue'
  import Editor from '@/components/Editor.vue'
  import { toast } from '@/utils'

  const emit = defineEmits(['reloadData'])
  const formDrawerRef = ref(null)
  const form = reactive({
    content: '',
  })

  function submit() {
    formDrawerRef.value.showLoading()
    updateGoodsApi(goodsId.value, form)
      .then((res) => {
        toast('设置商品详情成功')
        formDrawerRef.value.close()
        emit('reloadData')
      })
      .finally(() => formDrawerRef.value.hideLoading())
  }

  const goodsId = ref(0)
  function open(row) {
    goodsId.value = row.id
    row.contentLoading = true
    readGoodsApi(goodsId.value)
      .then((res) => {
        form.content = res.content
        formDrawerRef.value.open()
      })
      .finally(() => (row.contentLoading = false))
  }

  const formRef = ref(null)
  function handleCancel() {
    formRef.value.resetFields()
    formDrawerRef.value.close()
  }
  defineExpose({
    open,
  })
</script>

<style scoped></style>
